package com.rainng.coursesystem.module.custom.service.impl;

import cn.hutool.db.handler.StringHandler;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rainng.coursesystem.base.api.dto.PagingReqDTO;
import com.rainng.coursesystem.base.utils.BeanMapper;
import com.rainng.coursesystem.model.bo.LoginStatusBO;
import com.rainng.coursesystem.model.vo.response.ResultVO;
import com.rainng.coursesystem.module.custom.dto.request.CustomQueryReqDTO;
import com.rainng.coursesystem.module.custom.dto.request.CustomReqDTO;
import com.rainng.coursesystem.module.custom.dto.response.CusDicResDTO;
import com.rainng.coursesystem.module.custom.dto.response.CustomResDTO;
import com.rainng.coursesystem.module.custom.entity.Custom;
import com.rainng.coursesystem.module.custom.entity.CustomUser;
import com.rainng.coursesystem.module.custom.mapper.CustomMapper;
import com.rainng.coursesystem.module.custom.service.CustomService;
import com.rainng.coursesystem.module.custom.service.CustomUserService;
import com.rainng.coursesystem.module.system.dto.response.SysUserResDTO;
import com.rainng.coursesystem.module.system.entity.SysRole;
import com.rainng.coursesystem.module.system.entity.SysUser;
import com.rainng.coursesystem.module.system.service.SysGroupService;
import com.rainng.coursesystem.module.system.service.SysRoleService;
import com.rainng.coursesystem.module.system.service.SysUserService;
import com.rainng.coursesystem.module.task.dto.response.TaskCarResDTO;
import com.rainng.coursesystem.module.task.dto.response.TaskPagingResDTO;
import com.rainng.coursesystem.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CustomServiceImpl extends ServiceImpl<CustomMapper, Custom> implements CustomService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysGroupService sysGroupService;

    @Autowired
    private CustomUserService customUserService;

    @Autowired
    private UserService userService;

    @Autowired
    private SysRoleService sysRoleService;

    @Resource
    private CustomMapper customMapper;

    @Override
    public IPage<CustomResDTO> paging(PagingReqDTO<CustomQueryReqDTO> reqDTO) {
        ResultVO<Map<String,String>> vo = userService.getLoginStatusWithDepartment();
        String username = vo.getData().get("username");
        String groupName = vo.getData().get("groupName");
        String roleName = vo.getData().get("roleName");
        String userId = String.valueOf(vo.getData().get("uId"));
        log.info(vo.toString());
        reqDTO.getParams().setCreateBy(username);
        reqDTO.getParams().setUserId(userId);
        reqDTO.getParams().setRoleName(roleName);
        reqDTO.getParams().setGroup(groupName);
        IPage<CustomResDTO> res = null;
        String userType = String.valueOf(vo.getData().get("userType"));
        //1.超级管理员拿到所有数据
        if ("3".equals(userType) || "4".equals(userType)){

             res = convertPage(baseMapper.paging(reqDTO.toPage(),reqDTO.getParams()),reqDTO);
            return res;
        }else if ("2".equals(userType)){
            //3.组长角色,能够看到一个组内的信息
             res = convertPage(baseMapper.pagingByGroup(reqDTO.toPage(), reqDTO.getParams()),reqDTO);
            return res;
        }else if ("1".equals(userType)){
            //2.主检也只能看到主检等于自己的数据并且属于一个组
            res = convertPage(baseMapper.pagingByPerson(reqDTO.toPage(), reqDTO.getParams()),reqDTO);
            return res;
        }
        return res;
    }

    /**
     * 获取custom对应的user用户
     * @param page
     * @param reqDTO
     * @return
     */
    public IPage<CustomResDTO> convertPage(IPage<CustomResDTO> page, PagingReqDTO<CustomQueryReqDTO> reqDTO){
        List<Integer> list = new ArrayList<>();
        int index = -1;
        for (CustomResDTO custom : page.getRecords()) {
            index++;
            List<CustomUser> collect = new ArrayList<>();
            if (!StringUtils.isBlank(reqDTO.getParams().getCusName())){
                collect = customUserService.list(new LambdaQueryWrapper<CustomUser>().eq(CustomUser::getCustomId, custom.getId()).like(CustomUser::getCusName,reqDTO.getParams().getCusName()));
                if (collect.size() == 0){
                    list.add(index);
                }
            }else {
                collect = customUserService.list(new LambdaQueryWrapper<CustomUser>().eq(CustomUser::getCustomId, custom.getId()));
            }
            custom.setCustoms(collect);
        }
        for (int i = list.size()-1; i >= 0; i--) {
            page.getRecords().remove((int)list.get(i));
        }
//        for (int i : list) {
//            if (page.getRecords().size() > 0){
//                page.getRecords().remove(i);
//            }
//        }
        return page;
    }


    @Override
    public void save(CustomReqDTO reqDTO) {
        Custom custom = new Custom();
        BeanMapper.copy(reqDTO,custom);
        ResultVO<Map<String,String>> vo = userService.getLoginStatusWithDepartment();
        String username = vo.getData().get("username");
        String groupId = vo.getData().get("groupId");
        String id = IdWorker.getIdStr();
        if (StringUtils.isBlank(custom.getId())){
            custom.setId(id);
            custom.setCreateBy(username);
            custom.setGroupId(groupId);
            this.save(custom);
        }else {
            custom.setUpdateBy(username);
            custom.setGroupId(groupId);
            baseMapper.updateById(custom);
        }
    }

    @Override
    public CustomResDTO getCustomById(String id) {
        Custom custom = baseMapper.selectById(id);
        if (custom == null) return null;
        CustomResDTO resDTO = new CustomResDTO();
        BeanMapper.copy(custom,resDTO);
        ResultVO<Map<String,String>> vo = userService.getLoginStatusWithDepartment();
        String username = vo.getData().get("username");
        String groupName = vo.getData().get("departName");
        resDTO.setUserName(username);
        resDTO.setGroupName(groupName);
        return resDTO;
    }

    @Override
    public List<CusDicResDTO> getList() {
        ResultVO<Map<String,String>> vo = userService.getLoginStatusWithDepartment();
        String groupId = vo.getData().get("groupId");
        String roleId = String.valueOf(vo.getData().get("userType"));
//        SysRole role = sysRoleService.getById(roleId);
        if ( "3".equals(roleId) || "4".equals(roleId) ){
            List<Custom> list = this.list();
            List<CusDicResDTO> collect = list.stream().map(custom -> new CusDicResDTO(custom.getId(),
                    custom.getComName())).distinct().collect(Collectors.toList());
            return collect;
        }else {
            if ( "5".equals(roleId) || "6".equals(roleId) || "7".equals(roleId)){
                groupId = "1688826189812711425";
            }

            List<String> list = sysUserService.list(new LambdaQueryWrapper<SysUser>().
                    eq(SysUser::getGroupId, groupId))
                    .stream()
                    .map(e -> e.getId())
                    .collect(Collectors.toList());
            LambdaQueryWrapper<Custom> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(Custom::getUserId,list);
            List<Custom> customs = baseMapper.selectList(queryWrapper);
            List<CusDicResDTO> collect = customs.stream().map(custom -> new CusDicResDTO(custom.getId(),
                    custom.getComName())).distinct().collect(Collectors.toList());
            return collect;
        }
    }

    @Override
    @Transactional
    public void delete(List<String> ids) {
        this.removeByIds(ids);
        LambdaQueryWrapper<CustomUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(CustomUser::getCustomId,ids);
        List<CustomUser> userList = customUserService.list(queryWrapper);
        List<String> idsStr = userList.stream().map(e -> e.getId()).collect(Collectors.toList());
        customUserService.removeByIds(idsStr);
    }
    public List<CustomResDTO> getUserByCustomer(String customerId) {
        List<CustomResDTO> res;
        res = customMapper.getUserByCustomer(customerId);
        System.out.println(res);

        return res;
    }
}
